package com.pangu.web.handler.admin.system;

import com.pangu.web.handler.Handler;
import com.pangu.web.handler.admin.annotation.OpeLog;
import com.pangu.web.handler.admin.shiro.ShiroUtils;
import com.pangu.web.handler.admin.shiro.entity.UserOnline;
import com.pangu.web.handler.admin.shiro.service.SessionService;
import com.pangu.web.handler.admin.user.SysMenuEntity;
import com.pangu.web.handler.admin.user.SysRoleEntity;
import com.pangu.web.handler.admin.user.SysUserEntity;
import com.pangu.web.handler.admin.utils.StringUtils;
import com.pangu.web.handler.admin.utils.TokenManager;
import com.pangu.web.service.SysUserService;
import com.pangu.web.service.repository.jpa.SysMenuRepository;
import com.pangu.web.service.repository.jpa.SysRoleRepository;
import com.pangu.web.service.repository.jpa.SysUserRepository;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.*;

/**
 * @author Chris
 * @date 2018/4/21 16:32
 * @todo   用户管理控制层
*/
@Controller
@RequestMapping("/admin/user")
public class UserController  extends Handler{

    @Autowired
    private SysRoleRepository sysRoleRepository;
    @Autowired
    private SysMenuRepository sysMenuRepository;
    @Autowired
    private SysUserRepository sysUserRepository;

    @Autowired
    private SysUserService sysUserService;

     @Autowired
     private SessionService sessionService;


    /**
     * @author Chris
     * @date 2018/4/21 18:45
     * @todo  用户查询首页
    */
    @RequestMapping("/userIndex")
    @RequiresPermissions("sys:user:select")
    public ModelAndView index(HttpServletRequest request){

        ModelAndView modelAndView=new ModelAndView("/system/user/user");
        Page<SysUserEntity> page=sysUserRepository.findAll( new PageRequest(super.getP(request), super.getPs(request), Sort.Direction.ASC, "createTime"));
        List<SysUserEntity> userEntityList=page.getContent();
        List<UserOnline> userOnlineList=sessionService.list();
       for(int i=0;i<userEntityList.size();i++){
           for(int j=0;j<userOnlineList.size();j++){
               if(userOnlineList.get(j).getUsername().equalsIgnoreCase(userEntityList.get(i).getUsername())){
                   userEntityList.get(i).setOnline(1);
                   userEntityList.get(i).setSessionId(userOnlineList.get(j).getId());
               }
           }
       }
           modelAndView.addObject("userList",userEntityList);
           modelAndView.addObject("page",page);
           modelAndView.addObject("roleList",sysRoleRepository.findAll());

        return modelAndView;
    }
    /**
     * @author Chris
     * @date 2018/4/21 18:51
     * @todo
    */
    @OpeLog("增加用户")
    @RequestMapping(value = "/addUser")
    @RequiresPermissions("sys:user:add")
    @ResponseBody
    public Map<String,Object> addUser(@Valid SysUserEntity sysUserEntity,HttpServletRequest request){
        SysUserEntity user= TokenManager.getUser();
        if(user==null){
            resultMap.put("message","请登录！");
            return resultMap;
        }
        try {
            sysUserService.saveSysUser(sysUserEntity,request);
            resultMap.put("status",200);
            resultMap.put("message","新增用户成功");
        } catch (Exception e) {
            resultMap.put("status","500");
            resultMap.put("message",e.getMessage());
            e.printStackTrace();
        }

        return resultMap;
    }

    /**
     * @author Chris
     * @date 2018/4/23 14:16
     * @todo  删除用户
    */
    @OpeLog("/删除用户")
    @RequestMapping("/deleteUser")
    @RequiresPermissions("sys:user:delete")
    @ResponseBody
    public Map<String,Object> deleteUser(SysUserEntity sysUserEntity,HttpServletRequest request){

        SysUserEntity user= TokenManager.getUser();
        if(user==null){
            resultMap.put("message","你已退出,请重新登录!");
            return resultMap;
        }
        //判断要删除的管理员是否存在
        try {
            SysUserEntity sue=sysUserRepository.findSysUserEntityByUsername(sysUserEntity.getUsername());
            if(sue==null){
                resultMap.put("message","管理员不存在");
                return resultMap;
            }else{
                Set<SysRoleEntity> set=sue.getSysRoleEntities();
                for( Iterator   it = set.iterator();  it.hasNext(); )
                {
                    SysRoleEntity sr=(SysRoleEntity) it.next();
                    if(sr.getRoleName().equalsIgnoreCase("admin")){
                        resultMap.put("message","系统管理员不能删除");
                        return resultMap;
                    }
                }
              sysUserRepository.delete(sue);
            }
            resultMap.put("status",200);
            resultMap.put("message","管理员删除成功");

        } catch (Exception e) {
            resultMap.put("status",500);
            resultMap.put("message",e.getMessage());
            return resultMap;
        }
        return resultMap;

    }

    /**
     * @author Chris
     * @date 2018/3/29 16:22
     * @todo  禁用/启用管理员
     */
    /*  @SysLog("禁用/启用管理员")*/
    @RequestMapping("/disable")
    @RequiresPermissions("sys:user:update")
    @ResponseBody
    public Map<String,Object> disableUser(SysUserEntity sysUserEntity,HttpServletRequest request){
        SysUserEntity user= TokenManager.getUser();
        if(user==null){
            resultMap.put("message","你已退出,请重新登录!");
            return resultMap;
        }
        try {
            SysUserEntity sue=sysUserRepository.findSysUserEntityByUserId(sysUserEntity.getUserId());
            if(sue==null){
                resultMap.put("message","管理员不存在");
                return resultMap;
            }else{
                Set<SysRoleEntity> set=sue.getSysRoleEntities();
                for( Iterator   it = set.iterator();  it.hasNext(); )
                {
                    SysRoleEntity sr=(SysRoleEntity) it.next();
                    if(sr.getRoleName().equalsIgnoreCase("admin")){
                        resultMap.put("message","系统管理员不能修改");
                        return resultMap;
                    }
                }
                if(sysUserEntity.getStatus()==1){
                    sue.setStatus(0);
                }else{
                    sue.setStatus(1);
                }
                sysUserRepository.save(sue);
                resultMap.put("status",200);
                resultMap.put("message","禁用/启用成功");
            }
         } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("message","禁用/启用失败");
        }
        return resultMap;
    }

    /**
     * @author Chris
     * @date 2018/4/21 18:46
     * @todo  角色查询首页
    */
    @RequestMapping("/roleIndex")
    @RequiresPermissions("sys:role:select")
    public ModelAndView roleIndex(ModelMap map , HttpServletRequest request , @Valid String role) {
        List<SysRoleEntity> list=sysRoleRepository.findAll();
        return new ModelAndView("/system/role/role","list",list);
    }

    /**
     * @author Chris
     * @date 2018/4/21 14:25
     * @todo 角色-菜单查询
     */
    @RequestMapping("/roleInfo")
    @RequiresPermissions("sys:role:select")
    @ResponseBody
    public Map<String,Object> info(Long roleId){
        List<SysMenuEntity> list=sysMenuRepository.findAll();//查询所有菜单权限

        SysRoleEntity sr=sysRoleRepository.findByRoleId(roleId);//查询角色所对应的菜单ID
        Set<SysMenuEntity> menuSet=new HashSet<>();
        if(sr!=null){
            menuSet=sr.getSysMenuEntities();
        }


        StringBuffer sb=new StringBuffer();
        sb.append("[");
        int index=0;
        for(int i=0;i<list.size();i++){
            if(list.get(i).getParentId()==0){//如果父类ID等于0
                if(index==0){
                    if(menuSet.contains(list.get(i))){
                        sb.append("{\"title\":\""+list.get(i).getName()+"\",\"value\":\""+list.get(i).getMenuId()+"\",\"checked\":\"true\",\"data\":[");
                    }else {
                        sb.append("{\"title\":\""+list.get(i).getName()+"\",\"value\":\""+list.get(i).getMenuId()+"\",\"data\":[");
                    }

                }else {
                    if(menuSet.contains(list.get(i))){
                        sb.append(",{\"title\":\""+list.get(i).getName()+"\",\"value\":\""+list.get(i).getMenuId()+"\",\"checked\":\"true\",\"data\":[");

                    }else {
                        sb.append(",{\"title\":\""+list.get(i).getName()+"\",\"value\":\""+list.get(i).getMenuId()+"\",\"data\":[");

                    }
                }
                index++;
                int flag=0;
                for(int j=0;j<list.size();j++){
                    if(list.get(i).getMenuId()==list.get(j).getParentId()){
                        if (flag == 0) {
                            if (menuSet.contains(list.get(j))) {
                                sb.append("{\"title\": \"" + list.get(j).getName() + "\", \"value\": \"" + list.get(j).getMenuId() + "\",\"checked\":\"true\", \"data\": []}");
                            } else {
                                sb.append("{\"title\": \"" + list.get(j).getName() + "\", \"value\": \"" + list.get(j).getMenuId() + "\", \"data\": []}");
                            }
                        } else {
                            if (menuSet.contains(list.get(j))) {
                                sb.append(",{\"title\": \"" + list.get(j).getName() + "\", \"value\": \"" + list.get(j).getMenuId() + "\",\"checked\":\"true\", \"data\": []}");
                            } else {
                                sb.append(",{\"title\": \"" + list.get(j).getName() + "\", \"value\": \"" + list.get(j).getMenuId() + "\", \"data\": []}");
                            }
                        }
                        flag++;
                    }
                }
                sb.append("]}");
            }
        }
        sb.append("]");

        resultMap.put("role",sb.toString());
        return resultMap;
    }

    /**
     * @author Chris
     * @date 2018/4/21 16:27
     * @todo  修改角色
     */
    @OpeLog("修改角色")
    @RequestMapping("/roleUpdate")
    @RequiresPermissions("sys:role:update")
    @ResponseBody
    public Map<String,Object> update(Long roleId,String roleName,String menId){
        if(roleName.equals("admin")){
            resultMap.put("status","301");
            resultMap.put("message","超级管理员不允许修改");
        }

        String [] array=menId.split("#");
        Set<SysMenuEntity> set=new HashSet<>();
        for(int i=0;i<array.length;i++){
            set.add(SysMenuEntity.of().setMenuId(Long.parseLong(array[i])));
        }
        SysRoleEntity sysRoleEntity= SysRoleEntity.of().setRoleId(roleId).setUpdateTime(new Date()).setSysMenuEntities(set).setRoleName(roleName);
        try {

            sysRoleRepository.save(sysRoleEntity);
            resultMap.put("message","修改成功！");
        } catch (Exception e) {
            resultMap.put("message","修改失败！");
            e.printStackTrace();
        }
        return resultMap;
    }

    /**
     * @author Chris
     * @date 2018/3/24 18:37
     * @todo  新增角色
     */
    @OpeLog("新增角色")
    @RequestMapping("/addRole")
    @RequiresPermissions("sys:role:add")
    @ResponseBody
    public Map<String,Object> addRole(String roleName,String menId){

        SysUserEntity user= TokenManager.getUser();
        if(user==null){
            resultMap.put("message","你已退出,请重新登录!");
            return resultMap;
        }
        if(StringUtils.isNotBlank(roleName)){

            try {
                SysRoleEntity sr=sysRoleRepository.findByRoleName(roleName);
                if(sr!=null){
                    resultMap.put("message","角色已经存在！");
                    return  resultMap;
                }
                String [] array=menId.trim().split("#");
                Set<SysMenuEntity> set=new HashSet<>();

                for(int i=0;i<array.length;i++){
                    if(!array[i].equals("")){
                        set.add(SysMenuEntity.of().setMenuId(Long.parseLong(array[i])));
                    }
                }
                SysRoleEntity sysRoleEntity= SysRoleEntity.of().setRoleName(roleName).setUpdateTime(new Date()).setSysMenuEntities(set);
                sysRoleRepository.save(sysRoleEntity);
                resultMap.put("message","新增角色成功");
            } catch (NumberFormatException e) {
                resultMap.put("message",e.getMessage());
                e.printStackTrace();
            }
        }else {
            resultMap.put("message","请输入角色名称");
       }
        return resultMap;
    }

    /**
     * @author Chris
     * @date 2018/4/23 16:24
     * @todo  删除角色
    */
    @OpeLog("删除角色")
    @RequestMapping("/deleteRole")
    @RequiresPermissions("sys:role:delete")
    @ResponseBody
    public Map<String, Object> deleteRole(Long roleId){

        SysUserEntity user= TokenManager.getUser();
        if(user==null){
            resultMap.put("message","你已退出,请重新登录!");
            return resultMap;
        }
        try {
            SysRoleEntity sysRoleEntity=sysRoleRepository.findByRoleId(roleId);
        if(sysRoleEntity==null){
            resultMap.put("message","角色不存在");
            return resultMap;
        }
            sysRoleRepository.delete(sysRoleEntity);
             resultMap.put("status",200);
            resultMap.put("message","删除角色成功");
           } catch (Exception e) {
            resultMap.put("message",e.getMessage());
            e.printStackTrace();
        }
        return  resultMap;
    }




    /**
     * @author Chris
     * @date 2018/4/23 18:50
     * @todo  修改密码
    */
    @GetMapping(value = "/pas")
    public ModelAndView updatePassword(){
        return new ModelAndView("/system/user/password","username",TokenManager.getUser().getUsername());
    }


    /**
     * @author Chris
     * @date 2018/4/23 19:51
     * @todo  修改用户密码
     */
    @OpeLog("修改密码")
    @RequestMapping(value = "/updatePas",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> password(String password, String newPassword) {
        SysUserEntity user = TokenManager.getUser();
        if (user == null) {
            resultMap.put("message", "请登录！");
            return resultMap;
        }
        if (StringUtils.isBlank(password)) {
            resultMap.put("message", "请输入原密码");
            return resultMap;
        }
        if (StringUtils.isBlank(newPassword)) {
            resultMap.put("message", "请输入新密码");
            return resultMap;
        }
        //原密码
        password = ShiroUtils.sha256(password, user.getSalt());
        //新密码
        newPassword = ShiroUtils.sha256(newPassword, user.getSalt());
        try {
            SysUserEntity userEntity = sysUserRepository.findSysUserEntityByUsernameAndPassword(user.getUsername(), password);
            if (userEntity == null) {
                resultMap.put("message", "密码不正确");
                return resultMap;
            }
            sysUserRepository.save(userEntity.setPassword(newPassword));
            resultMap.put("message", "修改成功");
        } catch (Exception e) {
            resultMap.put("message", e.getMessage());
            e.printStackTrace();
        }
        return resultMap;
    }

    /**
     * @author Chris
     * @date 2018/4/21 18:48
     * @todo 菜单查询首页
     */
    @RequestMapping(value = "/menuIndex")
    public ModelAndView menuIndex(ModelMap map ,HttpServletRequest request,@Valid String parentId){

        if(StringUtils.isNotBlank(parentId)){
            map.addAttribute("menuList", sysMenuRepository.findSysMenuEntityByParentId(Long.parseLong(parentId) , new PageRequest(super.getP(request), super.getPs(request) , Sort.Direction.DESC , "createTime")));

        }
        return request(super.createAdminTempletResponse("/system/menu/menu"));

    }

    /**
     * @author Chris
     * @date 2018/4/24 13:06
     * @todo   编辑主菜单
    */

    @RequestMapping("/editMainMenu")
    public ModelAndView editMainMenu(ModelMap map , HttpServletRequest request , @Valid String menuId) {
        map.addAttribute("menu", sysMenuRepository.findSysMenuEntityByMenuId(Long.parseLong(menuId))) ;
        return request(super.createRequestPageTempletResponse("/system/menu/editMainMenu"));
    }
   /**
    * @author Chris
    * @date 2018/4/24 19:08
    * @todo   编辑二级菜单
   */
    @RequestMapping("/editSecondMenu")
    public ModelAndView editSecondMenu (ModelMap map , HttpServletRequest request , @Valid String menuId) {
        map.addAttribute("menu", sysMenuRepository.findSysMenuEntityByMenuId(Long.parseLong(menuId))) ;
        return request(super.createRequestPageTempletResponse("/system/menu/editSecondMenu"));
    }
    /**
     * @author Chris
     * @date 2018/4/24 19:08
     * @todo   编辑子菜单
    */
    @RequestMapping("/editMenu")
    public ModelAndView editMenu(ModelMap map , HttpServletRequest request , @Valid String menuId) {
        map.addAttribute("menu", sysMenuRepository.findSysMenuEntityByMenuId(Long.parseLong(menuId))) ;
        return request(super.createRequestPageTempletResponse("/system/menu/editMenu"));
    }



    /**
     * @author Chris
     * @date 2018/4/24 13:59
     * @todo   修改菜单
    */
    @OpeLog(value = "修改菜单")
    @RequestMapping(value = "/updateMenu")
    public Map<String,Object>  updateMenu(@Valid SysMenuEntity sysMenuEntity){
        SysMenuEntity sme=sysMenuRepository.findSysMenuEntityByMenuId(sysMenuEntity.getMenuId());
        if(StringUtils.isNotBlank(sysMenuEntity.getName())){
            sme.setName(sysMenuEntity.getName());
        }
        if(StringUtils.isNotBlank(sysMenuEntity.getPerms())){
            sme.setPerms(sysMenuEntity.getPerms());
        }
        if(StringUtils.isNotBlank(sysMenuEntity.getIcon())){
            sme.setIcon(sysMenuEntity.getIcon());
        }
        try {
            sysMenuRepository.save(sme);
            resultMap.put("message","修改成功");
        } catch (Exception e) {
            resultMap.put("message",e.getMessage());
            e.printStackTrace();
        }
        return resultMap;
    }

    /**
     * @author Chris
     * @date 2018/4/24 19:44
     * @todo  删除菜单
    */

    @OpeLog(value = "删除菜单")
    @RequestMapping(value = "/deleteMenu")
    public Map<String,Object>  deleteMenu(@Valid String menuId){
        SysMenuEntity sme=sysMenuRepository.findSysMenuEntityByMenuId(Long.parseLong(menuId));
        if(sme==null){
            resultMap.put("message","菜单不存在");
            return resultMap;
        }
        try {
            sysMenuRepository.delete(menuId);
            resultMap.put("message","删除菜单成功");
        } catch (Exception e) {
            resultMap.put("message",e.getMessage());
            e.printStackTrace();
        }
        return resultMap;
    }
    /**
     * @author Chris
     * @date 2018/4/30 13:16
     * @todo  踢出管理员
    */
    @OpeLog(value = "踢出管理员")
    @RequestMapping(value = "/forceLogout")
    @ResponseBody
    public Map<String,Object> forceLogout(String userId,HttpServletRequest request){
        try {
            sessionService.forceLogout(userId);
            resultMap.put("message","踢出管理员成功");
        } catch (Exception e) {
            resultMap.put("message",e.getMessage());
            e.printStackTrace();
        }
        return resultMap;
    }

     /**
      * @author Chris
      * @date 2018/5/3 19:39
      * @todo   修改管理员角色
     */
    @OpeLog(value = "修改管理员角色")
    @RequestMapping(value = "/updateRole")
    @RequiresPermissions(value = "sys:user:update")
    @ResponseBody
    public Map<String,Object> updateRole(SysUserEntity sysUserEntity, HttpServletRequest request){
        try {
           if(sysUserEntity!=null){
               SysUserEntity sue=sysUserRepository.findSysUserEntityByUsername(sysUserEntity.getUsername());

               Set<SysRoleEntity> set=new HashSet<SysRoleEntity>();
               for (Long roleId:sysUserEntity.getRoleIdList()){
                   set.add(SysRoleEntity.of().setRoleId(roleId));
               }
               sue.setSysRoleEntities(set);
               sysUserRepository.save(sue);
               }
            resultMap.put("message","修改角色成功");
        } catch (Exception e) {
            resultMap.put("message",e.getMessage());
            e.printStackTrace();
        }
        return resultMap;
    }



}
